import { URLSearchParamsInit, useSearchParams } from "react-router-dom";
import { useMemo } from "react";
import { cleanObject } from "./index";
/**
 * 返回url中指定键的参数值
 * */

export const useUrlQueryParam = <K extends string>(keys: K[]) => {
  const [searchParams] = useSearchParams();
  const setSearchParams = useSetUrlSearchParam();
  // const [stateKeys] = useState(keys);
  return [
    useMemo(
      () =>
        keys.reduce((prev, key) => {
          return { ...prev, [key]: searchParams.get(key) || "" };
        }, {} as { [key in K]: string }),
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [searchParams]
    ),
    (params: Partial<{ [key in K]: unknown }>) => {
      // const o = cleanObject({...Object.fromEntries(searchParams), ...params}) as URLSearchParamsInit
      // // @ts-ignore: Unreachable code error
      // if(params.editingProjectId === 'undefined') {
      //   // @ts-ignore: Unreachable code error
      //   delete o.projectCreate
      //   // @ts-ignore: Unreachable code error
      //   delete o.editingProjectId
      // }
      // return setSearchParams(o)
      return setSearchParams(params);
    },
  ] as const;
};
export const useSetUrlSearchParam = () => {
  const [searchParams, setSearchParam] = useSearchParams();
  return (params: { [key in string]: unknown }) => {
    const o = cleanObject({
      ...Object.fromEntries(searchParams),
      ...params,
    }) as URLSearchParamsInit;
    return setSearchParam(o);
  };
};
// export const useSetUrlSearchParam = () => {
//   const [searchParams, setSearchParam] = useSearchParams();
//   return (params: { [key in string]: unknown }) => {
//     const o = cleanObject({
//       ...Object.fromEntries(searchParams),
//       ...params,
//     }) as URLSearchParamsInit;
//     return setSearchParam(o);
//   };
// };
